//
//  NSDate+Extension.m
//  1012weibo日期处理
//
//  Created by Apple on 15/11/12.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "NSDate+Extension.h"

@implementation NSDate (Extension)


///将新浪服务器返回的的日期字符串转换为系统日期
+ (NSDate *)dateWithSinaDateString:(NSString *)dateString
{
    //创建日期格式化器
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    //指定格式
    formatter.dateFormat = @"EEE MMM dd HH:mm:ss zzz yyyy";
    
    return [formatter dateFromString:dateString];
}


/*
 刚刚(一分钟内)
 X分钟前(一小时内)
 X小时前(当天)
 昨天 HH:mm(昨天)
 MM-dd HH:mm(一年内)
 yyyy-MM-dd HH:mm(更早期)
 */

///将日期转换成微博字符串
+ (NSString *)weiboDateStringWithDate:(NSDate *)date
{
    //定义日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    //今天
    if ([calendar isDateInToday:date])
    {
        //计算当前时间与date的时间差
        int time = (int)[[NSDate date] timeIntervalSinceDate:date];
        
        if (time < 60)
        {
            return @"刚刚";
        }
        else if (time < 60 * 60)
        {
            return [NSString stringWithFormat:@"%d分钟前", time / 60];
        }
        else
        {
            return [NSString stringWithFormat:@"%d小时前", time / 60 / 60];
        }
    }
    
    NSString *format = nil;
    
    //昨天
    if ([calendar isDateInYesterday:date])
    {
        format = @"昨天 HH:mm";
    }
    else
    {
        NSComparisonResult result = [calendar compareDate:date toDate:[NSDate date] toUnitGranularity:NSCalendarUnitYear];
        
        if (result == NSOrderedSame)  //一年内
        {
            format = @"MM-dd HH:mm";
        }
        else if (result == NSOrderedAscending)  //更早
        {
            format = @"yyyy-MM-dd HH:mm";
        }
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    formatter.dateFormat = format;
    
    return  [formatter stringFromDate:date];
}


@end
